package com.ahnu.tongue.aspect;

import com.ahnu.tongue.annotation.RateLimit;
import com.ahnu.tongue.common.BusinessException;
import com.google.common.util.concurrent.RateLimiter;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class RateLimitAspect {

    private final ApplicationContext applicationContext;

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint point, RateLimit rateLimit) throws Throwable {
        // 获取限流器
        RateLimiter limiter = applicationContext.getBean(rateLimit.limiter(), RateLimiter.class);
        
        // 尝试获取令牌
        if (!limiter.tryAcquire()) {
            throw new BusinessException(429, "请求过于频繁，请稍后再试");
        }
        
        return point.proceed();
    }
} 